<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }" >首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 用户列表主体 -->
        <el-card>

            <el-row :gutter="25"> 
                <el-col :span="10"> 
                    <!-- 搜索添加 -->
                    <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUserList()">
                        <el-button slot="append" icon="el-icon-search" @click="getNewUserList()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <!-- 点击添加用户改变addDialogVisible显示添加用户对话框 -->
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>            
            <!-- 用户列表 border边框 stripe隔行变色 -->
            <el-table :data="userList" border stripe>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="用户名" prop="username"></el-table-column>
                <el-table-column label="密码" prop="password"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="角色" prop="role"></el-table-column>
                <el-table-column label="状态" prop="state">
                    <!-- 作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- {{scope.row}} 每一行封存的数据 -->
                        <el-switch v-model="scope.row.state" @change="userStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-tooltip effect="dark" content="修改用户信息" placement="top-start" :enterable="false"><!--文字提示 enterable 隐藏-->
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <!-- 删除 -->
                        <el-tooltip effect="dark" content="删除用户信息" placement="top-start" :enterable="false"><!--文字提示 enterable 隐藏-->
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                        </el-tooltip>
                        <!-- 权限 -->
                        <el-tooltip effect="dark" content="修改用户角色" placement="top-start" :enterable="false"><!--文字提示 enterable 隐藏-->
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRoleDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 size-change=每页最大变化  current-change=当前最大变化  layout=功能组件-->
            <div>
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pageNum"
                        :page-sizes="[1, 2, 5, 10]"
                        :page-size="queryInfo.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
            </div>
        </el-card>
        <!-- 创建新用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"  prefix-icon="iconfont icon-mima" ></el-input>
                </el-form-item>
                    <!-- 密码 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" prefix-icon="iconfont icon-denglu" show-password type="password"></el-input>
                </el-form-item>
                    <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" prefix-icon="iconfont icon-youxiang"></el-input>
                </el-form-item>
            </el-form>
            <!-- 内容底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @colse="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                    <!-- 用户名 -->
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="editForm.username" disabled></el-input>
                    </el-form-item>
                    <!-- 密码 -->
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="editForm.password"></el-input>
                    </el-form-item>
                    <!-- 邮箱 -->
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editForm.email"></el-input>
                    </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改权限对话框 -->
        <el-dialog title="修改用户角色" :visible.sync="roleDialogVisible" width="50%" @colse="roleDialogClosed">
            <el-form :model="roleForm"  ref="roleFormRef" label-width="70px">
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                     <el-input v-model="roleForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="roleForm.role" placeholder="请选择用户角色">
                        <el-option label="超级管理员" value="超级管理员"></el-option>
                        <el-option label="普通管理员" value="普通管理员"></el-option>
                        <el-option label="普通用户" value="普通用户"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeUserRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    created(){
        this.getUserList();
    },
    data()  {
        return {
            // 查询信息实体
            queryInfo:{
                query:"", // 查询信息
                pageNum: 1,// 当前页
                pageSize: 5,// 每页最大数
            },
            userList:[],// 用户列表
            total: 0,// 总记录数
            addDialogVisible: false ,// 添加用户对话框状态
            // 添加表单信息
            addForm:{
                username:'',
                password:'',
                email:'',
            },
            
            // 表单验证
            addFormRules:{
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 5, max: 12, message: '长度在 5 ~ 12 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 ~ 16 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 5, max: 15, message: '请输入正确邮箱地址', trigger: 'blur', type: 'email'}
                ],
            },
            // 修改用户信息
            editForm:{},
            // 控制修改用户对话框显示/隐藏
            editDialogVisible:false,
            // 修改用户表单验证规则
            editFormRules:{
                password:[
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 ~ 16 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 5, max: 15, message: '请输入正确邮箱地址', trigger: 'blur', type: 'email'}
                ],
            },
            // 控制修改用户对话框显示/隐藏
            roleDialogVisible:false,
            roleForm:{},
        }
    },
    methods:{
        // 获取用户列表
        async getUserList(){
            const {data:res} = await this.$http.get("allUser",{params:this.queryInfo});
            this.userList = res.data; // 用户列表数据封装
            this.total = res.userCounts;// 总用户数封装
        },
        // 监听pageSize改变的事件
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.queryInfo.pageNum = 1;
            this.getUserList(); // 数据发生改变重新申请数据
        },
        // 监听pageNum改变的事件
        handleCurrentChange(newPage) {
            this.queryInfo.pageNum = newPage;
	        this.getUserList(); // 数据发生改变重新申请数据
        },
        // 修改用户状态
        async userStateChange(userInfo){
            const { data: res } = await this.$http.put(
                `userState?id=${userInfo.id}&state=${userInfo.state}`
            );
            if (res != "success") {
                userInfo.state = !userInfo.state;
                return this.$message.error("操作失败！！！");
            }
            this.$message.success("操作成功！！！");
        },
        /** 当用户在非第一页查询时 执行搜索会跳过之前页面的数据
         * 为此我们将搜索按钮的click事件重新设计 先将pageNum设为1 再进行搜索
         */
        getNewUserList(){
            this.queryInfo.pageNum = 1;
            this.getUserList();
        },
         // 监听添加用户
        addDialogClosed(){
            this.$refs.addFormRef.resetFields();// 重置表单项
        },
        // 添加用户
        addUser(){
            this.$refs.addFormRef.validate(async valid =>{
                console.log(valid);
                if( !valid ) return;
                // 发起请求
                const {data:res} = await this.$http.post("addUser",this.addForm);
                if (res != "success") {
                    return this.$message.error("操作失败！！！");
                }
                this.$message.success("操作成功！！！");
                // 隐藏
                this.addDialogVisible = false;
                // 重新获取用户列表
                this.getUserList();
            })
        },
        // 删除按钮
        async deleteUser(id){
            // 弹窗确认操作
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 确定删除为confirm 取消为 cancel
            if(confirmResult!='confirm'){
                return this.$message.info("已取消删除");
            }
            const {data:res} = await this.$http.delete("deleteUser?id="+id);
            if (res != "success") {
                return this.$message.error("操作失败！！！");
            }
            this.$message.success("操作成功！！！");
            this.getUserList();
        },
        // 展示修改框
        async showEditDialog(id){
            const {data:res} = await this.$http.get("getUpdate?id="+id);
            this.editForm = res;
            this.editDialogVisible = true;
        },
        // 关闭窗口
        editDialogClosed(){
            this.$refs.editFormRef.resetFields();// 重置表单项
        },
        // 确认修改
        editUserInfo(){
            this.$refs.editFormRef.validate(async valid =>{
                console.log(valid);
                if( !valid ) return;
                // 发起请求
                const {data:res} = await this.$http.put("editUser",this.editForm);
                console.log(res);
                if (res != "success") return this.$message.error("操作失败！！！");
                this.$message.success("操作成功！！！");
                // 隐藏
                this.editDialogVisible = false;
                this.getUserList();
            });
        },
        // 展示权限框
        async showRoleDialog(id){
            const {data:res} = await this.$http.get("getUpdate?id="+id);
            this.roleForm = res;
            this.roleDialogVisible = true;
        },
        // 关闭窗口
        roleDialogClosed(){
            this.$refs.roleFormRef.resetFields();// 重置表单项
        },
        // 修改用户权限
        changeUserRole(){
            this.$refs.roleFormRef.validate(async valid =>{
                console.log(valid);
                if( !valid ) return;
                // 发起请求
                const {data:res} = await this.$http.put("changeRole",this.roleForm);
                console.log(res);
                if (res != "success") return this.$message.error("操作失败！！！");
                this.$message.success("操作成功！！！");
                // 隐藏
                this.roleDialogVisible = false;
                this.getUserList();
            });
        },
    },
}
</script>

<style lang="less" scoped></style>
